package com.zhang.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class CookieUtil {

    public static  void addCookie(String cookieName, int time, HttpServletRequest req, HttpServletResponse resp , String username , String password){


        //覆盖掉原始的用户名密码
        Cookie cookie = getCookieByName(req, cookieName);
        if(cookie != null){
            cookie.setValue(username+"#"+password);
        }else{
            try {
                cookie = new Cookie(cookieName, URLEncoder.encode(username,"utf-8")+"#"+password); //URLEncoder.encode(username,"utf-8") 防止cookie中文乱码, 所以要采用url编码
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }


        cookie.setMaxAge(time);//设置cookie最大存活时间(单位s)
        cookie.setPath(req.getContextPath());//设置cookie的有效范围(当前项目)
        resp.addCookie(cookie);//添加响应头Set-Cookie:k=v
    }

    //根据cookie名查询cookie
    public static Cookie getCookieByName(HttpServletRequest req,String cookieName){
        Cookie[] cookies = req.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(cookieName)){
                    return cookie;
                }
            }
        }

        return null;
    }


}
